# Example demostrating how to use the api library
#
# Authors: Wojciech Mlynarczyk

include "/etc/varnish/varnish-apikey.vcl";

backend wikipedia {
	.host = "208.80.152.201";
	.port = "80";
}

#
# Subroutine that defines the api, key and token.
#
sub recognize_apiname_apikey_token {
	# Identify api
	if (req.url ~ "^/tomato") {
		set req.http.apiname = "tomato";
	} else if (req.url ~ "^/potato") {
		set req.http.apiname = "potato";
	} else if (req.url ~ "^/apple") {
		set req.http.apiname = "apple";
	} else {
		error 400 "Unknown api.";
	}

	# Save apikey
	set req.http.apikey = regsub(req.url, ".*[?;]apikey=([^;]*).*", "\1");

	# Save token
	set req.http.token = regsub(req.url, ".*[?;]token=([^;]*).*", "\1");
}

sub vcl_recv {
	# Validate apikey using apikey library.
	call validate_api;

	# Proxy to wikipedia to simulate api request.
	if (req.url ~ "^/tomato") {
		set req.url = "/wiki/Tomato";
	} else if (req.url ~ "^/potato") {
		set req.url = "/wiki/Potato";
	} else {
		set req.url = "/wiki/Apple";
	}

	set req.http.host = "en.wikipedia.org";
	set req.backend = wikipedia;
}
